package com.neuedu.it.teach.service.impl;

import com.neuedu.it.teach.controller.vo.OrderDetailVO;
import com.neuedu.it.teach.dao.OrderDao;
import com.neuedu.it.teach.service.HelpService;
import com.neuedu.it.teach.entity.Help;

import com.neuedu.it.teach.entity.OrderStatus;
import com.neuedu.it.teach.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao mapper;

    @Autowired
    private  HelpService helpMapper;

    @Override
    public OrderStatus createOrder(OrderStatus order) {
        order.setTeacherConfirmed(false);
        order.setParentConfirmed(false);
        order.setTeacherAcceptAt(LocalDateTime.now());
        mapper.insertOrder(order);
        return order;
    }

    @Override
    public List<OrderStatus> getAllOrders() {
        return mapper.getAllOrders();
    }

    @Override
    public List<OrderDetailVO> getOrdersByUser(Integer teacherId, Integer helpId, Integer userId) {
        if (teacherId != null) {
            return mapper.getOrdersByTeacherId(teacherId);
        } else if (helpId != null) {
            return mapper.getOrdersByHelpId(helpId);
        } else {
            return mapper.getOrdersByUserId(userId);
        }
    }


    @Override
    public OrderStatus updateTeacherConfirmed(Integer orderId) {
        mapper.confirmTeacher(orderId);
        OrderStatus order = mapper.getById(orderId);
        if (order.getParentConfirmed()) {
            mapper.setCompletedTime(orderId);
            order.setCompletedAt(LocalDateTime.now());
            helpMapper.updateHelp(order.getHelpId(), "completed");
        }
        order.setTeacherConfirmed(true);
        return order;
    }

    @Override
    public OrderStatus updateParentConfirmed(Integer orderId) {
        mapper.confirmParent(orderId);
        OrderStatus order = mapper.getById(orderId);
        if (order.getTeacherConfirmed()) {
            mapper.setCompletedTime(orderId);
            order.setCompletedAt(LocalDateTime.now());
            helpMapper.updateHelp(order.getHelpId(), "completed");
        }
        order.setParentConfirmed(true);
        return order;
    }
    @Override
    public int deleteOrderById(int orderId) {
        OrderStatus order = mapper.getById(orderId);
        helpMapper.updateHelp(order.getHelpId(), "pending");
        return mapper.deleteById(orderId);
    }
}
